package user

import (
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"socket/common"
	"socket/model"
	"socket/model/user"
)

type UserJson struct {
	Id        int            `json:"id"`
	Username  string         `json:"username"`
	Avatar    string         `json:"avatar"`
	CreatedAt model.Time     `json:"created_at"`
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Sn        string         `json:"sn"`
}

func (UserJson) TableName() string {
	return "users"
}

type UserRequest struct {
	Username string `json:"username" validate:"required" label:"登录名"`
	Password string `json:"password"  label:"密码"`
}

type AdminUserController struct {
	//需要DB连接操作数据库
	DB *gorm.DB
}

func Reg(ctx *gin.Context) {
	DB := common.GetDB()
	var requestModel UserRequest
	_ = ctx.ShouldBindJSON(&requestModel)

	if err := common.Validate.Struct(requestModel); err != nil {
		common.Fail(ctx, common.Translate(err), nil)
		return
	}
	//密码加密
	if requestModel.Password == "" {
		common.Fail(ctx, "密码不能为空", nil)
		return
	}
	hasePassword, err := bcrypt.GenerateFromPassword([]byte(requestModel.Password), bcrypt.DefaultCost)
	if err != nil {
		common.Server(ctx, "加密失败", nil)
		return
	}

	//判断数据库中是否存在
	var list user.User
	DB.Where("username=?", requestModel.Username).First(&list)
	if list.ID > 0 {
		common.Fail(ctx, "该用户已存在", nil)
		return
	}

	//数据库插入数据
	user := user.User{
		Username: requestModel.Username,
		Password: string(hasePassword),
		Avatar:   "https://upload.file.jingcaijinghe.com/files/img/2023/10/16/1697441004126190.jpg",
		Sn:       uuid.NewV4(),
	}

	if err := DB.Create(&user).Error; err != nil {
		panic(err)
	}

	//成功返回
	common.Success(ctx, nil, "注册成功")
}

func Login(ctx *gin.Context) {
	DB := common.GetDB()
	var requestModel UserRequest
	_ = ctx.ShouldBindJSON(&requestModel)
	if err := common.Validate.Struct(requestModel); err != nil {
		common.Fail(ctx, common.Translate(err), nil)
		return
	}
	//判断手机号是否存在
	var user user.User
	DB.Where("username=?", requestModel.Username).First(&user)
	if user.ID == 0 {
		common.Fail(ctx, "用户不存在", nil)
		return
	}

	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(requestModel.Password)); err != nil {
		common.Fail(ctx, "密码错误", nil)
		return
	}
	//发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		common.Server(ctx, "token发放失败", nil)
		return
	}

	//返回结果
	common.Success(ctx, gin.H{"token": token}, "登录成功")
}

func Info(ctx *gin.Context) {
	userList, _ := ctx.Get("UserList")
	common.Success(ctx, gin.H{"data": userList}, "成功")
}

func List(ctx *gin.Context) {
	//获取分页参数
	userId, _ := ctx.Get("UserId")
	DB := common.GetDB()
	var userLists []UserJson
	DB.Order("created_at desc").Not("id = ?", userId).Find(&userLists)

	//数据总数
	var total int64
	DB.Model(&userLists).Count(&total)
	common.Success(ctx, gin.H{"data": userLists, "total": total}, "成功")
}

func Show(ctx *gin.Context) {
	DB := common.GetDB()
	//获取path中的参数  获取的是字符串，强转成int
	modelSn := ctx.Params.ByName("sn")

	//判断数据库中是否存在
	var list UserJson
	DB.Where("sn=?", modelSn).First(&list)

	//返回
	common.Success(ctx, gin.H{"data": list}, "成功")
}
